local sk__caijian = fk.CreateSkill {

  name = "sk__caijian",

  tags = {},

}



sk__caijian:addEffect("active", {
  name = "sk__caijian",
  anim_type = "control",
  card_num = 0,
  target_num = 1,
  prompt = "#sk__caijian",
  derived_piles = "sk__xinxianying_jian",
  can_use = function(self, player)
    return player:usedSkillTimes(sk__caijian.name, Player.HistoryPhase) - player:getMark("sk__caijian_trigger-phase") < 1
  end,
  card_filter = Util.FalseFunc,
  target_filter = function(self, player, to_select, selected, selected_cards)
    return #selected == 0 and not to_select:isNude()
  end,
  on_use = function(self, room, effect)
    local player = effect.from
    local target = effect.tos[1]
    local card = room:askToChooseCard(player, {
      target = target,
      flag = "he",
      skill_name = sk__caijian.name,
      prompt = "#sk__caijian_choose::" .. target.id
    })
    local yes = false
    if Fk:getCardById(card).color == Card.Black and
        table.every(player:getPile("sk__xinxianying_jian"), function(id)
          return Fk:getCardById(id).suit ~= Fk:getCardById(card).suit and Fk:getCardById(id).suit ~= Card.NoSuit
        end) then
      yes = true
    end
    player:addToPile("sk__xinxianying_jian", card, true, sk__caijian.name, player.id)
    if yes and not target.dead then
      target:turnOver()
    end
  end,
})

sk__caijian:addEffect(fk.Damaged, {
  name = "#sk__caijian_trigger",
  mute = true,
  --sk__caijian,
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(sk__caijian.name) and
        table.find(player.room.alive_players, function(p)
          return not p:isNude()
        end)
  end,
  on_trigger = function(self, event, target, player, data)
    self.cancel_cost = false
    for _ = 1, data.damage do
      if player.dead or self.cancel_cost or
          table.every(player.room.alive_players, function(p)
            return p:isNude()
          end) then
        return
      end
      self:doCost(event, target, player, data)
    end
  end,
  on_cost = function(self, event, target, player, data)
    local targets = table.map(table.filter(player.room.alive_players, function(p)
      return not p:isNude()
    end), Util.IdMapper)
    local to = player.room:askForChoosePlayers(player, targets, 1, 1, "#sk__caijian", "sk__caijian", true)
    if #to > 0 then
      event:setCostData(self, to[1])
      return true
    end
    self.cancel_cost = true
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    room:addPlayerMark(player, "sk__caijian_trigger-phase", 1)
    player:broadcastSkillInvoke("sk__caijian")
    room:notifySkillInvoked(player, "sk__caijian", "masochism")
    local sk__caijian_skill = Fk.skills["sk__caijian"]
    sk__caijian_skill:onUse(room, {
      from = player,
      tos = { room:getPlayerById(event:getCostData(self)) },
    })
  end,
})

return sk__caijian
